import express from "express";
import jwt from "jsonwebtoken";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
const __filenameNew = fileURLToPath(import.meta.url);
const __dirnameNew = path.dirname(__filenameNew);
const data = fs.readFileSync(path.join(__dirnameNew, "./data.json"));
const dataJson = JSON.parse(data);
let indexRouter = express.Router();

indexRouter.get("/query", (req, res) => {
  res.send({
    message: "ok",
    status: 200,
  });
});
indexRouter.post("/login", (req, res) => {
  const { password, username } = req.body;
  console.log(password, username);
  let content = { username: username };
  let token = jwt.sign(content, "cheng", {
    expiresIn: 600 * 60 * 1, // 1小时过期
  });
  if (username == "admin" && password == "admin") {
    res.send({
      message: "登录成功",
      status: "200",
      token: token,
    });
  } else {
    res.send({
      message: "账号或密码错误",
      status: "10010",
    });
  }
});

indexRouter.get("/getUserMenu", (req, res) => {
  const token = req.headers.authorization?.split(" ")[1];
  jwt.verify(token, "cheng", (err, decoded) => {
    if (err) {
      return res.json({ code: "403", msg: "token无效" });
    }
  });
  res.send({
    status: 200,
    message: "success",
    data: dataJson,
  });
});

export default indexRouter;
